package com.ctrip.ibu.member.client.producer;


import com.ctrip.ibu.member.client.common.BrokerStatusUtil;
import com.ctrip.ibu.member.client.module.BrokerInfo;
import com.ctrip.ibu.member.client.module.TopicMessage;
import com.ctrip.ibu.member.common.util.NumberUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.validation.constraints.NotNull;
import java.util.List;


/**
 * 生产者client, 生产消息
 *
 * @author he.shaorong
 * @create 2023/3/27 15:26
 * @since 1.0.0
 */
public class ProducerClient {

    private static final Logger logger = LoggerFactory.getLogger(ProducerClient.class);

    /**
     * 生产消息
     *
     * @param topicMessage 消息内容
     * @return 生产是否成功
     */
    public static boolean sendMessage(@NotNull TopicMessage topicMessage) {
        //向nameserver查询可用的broker
        List<BrokerInfo> ipList = BrokerStatusUtil.getAliveBrokerIpList().getBrokerInfoList();
        if (ipList.isEmpty()) {
            return false;
        }

        //随机选择一个broker发送消息
        BrokerInfo brokerInfo = ipList.get(NumberUtil.getRandom(ipList.size()));
        String ip = brokerInfo.getIp();
        logger.info("send a message, broker ip"+ ip + ", topic:"+ topicMessage.getTopic() + " , message:", topicMessage.getMessageList().toString());
        return BrokerStatusUtil.sendToMessageBroker(ip, topicMessage);
    }


}
